﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Business.EntityFrameworkCore;
using mozhi.smarterp.Business.Sales;
using mozhi.smarterp.Business.Sales.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Business.Repositories.Sale
{
    public class SaleQuotationRepository : DocumentEfCoreRepository<BusinessDbContext, SaleQuotation, Guid> , ISaleQuotationRepository
    {
        public SaleQuotationRepository(IDbContextProvider<BusinessDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> GetCountAsync(string keyword, string number, Guid? customerId, Guid? currencyId, Guid? excludeId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<SaleQuotation>().AsNoTracking()
                .WhereIf(keyword.IsNullOrEmpty(), x => x.Number.Contains(keyword))
                .WhereIf(number.IsNullOrEmpty(), x => x.Number==number)
                .WhereIf(customerId.HasValue, x => x.CustomerId== customerId)
                .WhereIf(currencyId.HasValue, x => x.CurrencyId == currencyId)
                .WhereIf(excludeId.HasValue, x => x.Id != excludeId)
                .CountAsync();

            return count;
        }

        public async Task<List<SaleQuotation>> GetPagedListAsync(string keyword, string number, Guid? customerId, Guid? currencyId, int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var query = includeDetails ? (await WithDetailsAsync()).AsNoTracking() : dbContext.Set<SaleQuotation>().AsNoTracking();

            var saleQuotations = await query
                .WhereIf(keyword.IsNullOrEmpty(), x => x.Number.Contains(keyword))
                .WhereIf(number.IsNullOrEmpty(), x => x.Number == number)
                .WhereIf(customerId.HasValue, x => x.CustomerId == customerId)
                .WhereIf(currencyId.HasValue, x => x.CurrencyId == currencyId)
                .OrderByIf<SaleQuotation , IQueryable<SaleQuotation>>(!sorting.IsNullOrEmpty() , sorting)
                .PageBy(skipCount , maxResultCount)
                .ToListAsync();

            return saleQuotations;
        }
    }
}
